<!-- 对话列表 -->
<template>
  <div class="conversation-list">
    <div 
      class="item border-gray-300 border-t cursor-pointer hover:bg-green-50 p-2"
      :class="{
        'bg-green-50': conversationStore.selectedId === item.id,
        'bg-white': conversationStore.selectedId !== item.id,
      }"
      v-for="item in items"
      :key="item.id"
      @contextmenu.prevent="showContextMenu(item.id)"
      @mouseenter="hoverItemId = item.id"
      @mouseleave="hoverItemId = 0"
    >
      <a @click.prevent="goToConversation(item.id)">
        <div class="flex justify-between items-center text-sm leading-5 text-gray-500">
          <span>{{ item.selectedModel }}</span>
          <span>{{ dayjs(item.updatedAt).format('YYYY-MM-DD') }}</span>
        </div>
        <div class="flex items-center">
          <h2 class="flex-1 font-semibold leading-6 text-gray-900 truncate">{{item.title}}</h2>
          <Icon
            v-if="hoverItemId == item.id"
            class="text-green-900 transition-all duration-200"
            icon="line-md:trash"
            @click.stop="() => conversationStore.deleteConversation(item.id)"
          />
        </div>
      </a>
    </div>
  </div>
</template>
  
<script lang="ts" setup>
import dayjs from 'dayjs'
import { onMounted, ref } from 'vue'
import { Icon } from "@iconify/vue"
import { useRouter } from 'vue-router'
import { ConversationProps } from '../types'
import { useConversationStore } from "../stores/conversation"

defineProps<{ items: ConversationProps[] }>()
const router = useRouter()
const conversationStore = useConversationStore()
const hoverItemId = ref(0)

// 通知 Electron 显示右键菜单
const showContextMenu = (id: number) => {
  window.electronAPI.showContextMenu(id)
}

onMounted(() => {
  // 删除对话
  window.electronAPI.onDeleteConversation(async (id: number) => {
    await conversationStore.deleteConversation(id)
    if (conversationStore.selectedId === id) {
      conversationStore.selectedId = -1
      router.push('/')
    }
  })
})

// 跳转指定对话
const goToConversation = (id: number) => {
  router.push({ path: `/conversation/${id}`})
  conversationStore.selectedId = id
}
</script>